package rmi;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class CircServidor extends UnicastRemoteObject implements
		CircServerInterface {

	protected CircServidor() throws RemoteException {
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -8061101079589896457L;

	@Override
	public byte[][] getCircles(byte[][] pic, int IMG_SIZE)
			throws RemoteException {
		byte[][] npic = new byte[IMG_SIZE/2][IMG_SIZE];

		int X = IMG_SIZE/2;
		int Y = IMG_SIZE;
		int[][] A = new int[X][Y]; // int[X][Y][R];
		int pixel;
		int r;
		int maxA = 0;

		for (int y = 0; y < Y; y++) {
			for (int x = 0; x < X; x++) {
				pixel = pic[x][y];
				if (pixel > 0) {
					// this point needs to be considered in the accumulator.
					// plug for x0,y0 and get r.
					for (int x0 = 0; x0 < X; x0++) {
						for (int y0 = 0; y0 < Y; y0++) {
							r = (int) Math.sqrt((x - x0) * (x - x0) + (y - y0)
									* (y - y0));
							if ((r >= 3) && (r < 50)) { // increment
								// accumulator;
								A[x0][y0]++;// A[x0][y0][r]++;
								if (A[x0][y0] > maxA)
									maxA = A[x0][y0];
							}
						}
					}

				}
			}
		}

		for (int y = 0; y < Y; y++)
			for (int x = 0; x < X; x++)
				npic[x][y] = (byte) ((A[x][y] * 127) / maxA);
		System.out.println("Servidor repondeu...");
		return (npic);
	}

	public static void main(String[] args) {
		/*
		 * install RMI security manager
		 */
		System.setSecurityManager(new RMISecurityManager());
		/*
		 * arg[0] = rmi url
		 */
		if (args.length != 1) {
			System.err.println("Comando: CircServidor <server-rmi-url>");
			System.exit(-1);
		}
		try {
			// name with which we can find it = user name
			String name = args[0];
			// create new instance
			CircServidor server = new CircServidor();
			// register with nameserver
			Naming.rebind(name, server);
			System.out.println("Servidor CircServidor iniciado com nome: "
					+ name);
		} catch (Exception e) {
			System.out.println("Caught exception while registering: " + e);
			System.exit(-1);
		}
	}

}
